package com.quasar.hpatient.base;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;

import com.quasar.hpatient.Jpush.MyAlertDialog;
import com.quasar.hpatient.Jpush.NetBroadcastReceiver;
import com.quasar.hpatient.Jpush.NewWorkUtils;
import com.quasar.hpatient.R;
import com.quasar.hpatient.model.event.CloseEvent;
import com.quasar.hpatient.utils.LogAndToastUtil;
import com.quasar.hpatient.view.LoginActivity;
import com.quasar.hpatient.view.LoginActivity_;

import org.greenrobot.eventbus.EventBus;

/**
 * author : 许建宏
 * Date: 2017/9/26 0026
 */

public abstract class BaseActivity extends AppCompatActivity implements NetBroadcastReceiver.NetChangeListener {

    private Toolbar main_toolbar;
    public ProgressDialog pd;

    /**
     * 网络类型
     */
    private int netType;
    private NetBroadcastReceiver netBroadcastReceiver;
    public static NetBroadcastReceiver.NetChangeListener listener;
    private MyAlertDialog alertDialog = null;

    public void initToolbar() {
        main_toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        if (main_toolbar != null) {
            setSupportActionBar(main_toolbar);
            main_toolbar.setNavigationIcon(R.mipmap.ic_action_back);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_action_back);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId_ = item.getItemId();
        if (itemId_ == android.R.id.home) {
           finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        listener = this;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //实例化IntentFilter对象
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            netBroadcastReceiver = new NetBroadcastReceiver();
            //注册广播接收
            registerReceiver(netBroadcastReceiver, filter);
        } else {
            //实例化IntentFilter对象
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            netBroadcastReceiver = new NetBroadcastReceiver();
            //注册广播接收
            registerReceiver(netBroadcastReceiver, filter);
        }
        checkNet();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //当前界面销毁时对ProgressDialog进行关闭
        unregisterReceiver(netBroadcastReceiver);//注销广播
        //当前界面销毁时对ProgressDialog进行关闭
        if (pd != null) {
            pd.dismiss();
        }

    }

    //初始化控件
    protected abstract void initView();

    //数据初始化
    protected abstract void initData();

    //弹出消息
    public void msg(String msg){
        LogAndToastUtil.toast(this, msg, "");
        if(msg.equals("0xFFFFFFF4")){
            LoginActivity_.intent(this).start();
            finish();
            EventBus.getDefault().post(new CloseEvent());
        }
    }

    public void showDialog() {
        pd = new ProgressDialog(this);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
            }
        });
        pd.setMessage(getString(R.string.st_loading));
        pd.show();
    }

    public void dessDialog(){
        if(pd!=null){
            pd.dismiss();
        }
    }


    /**
     * 初始化时判断有没有网络
     */
    public boolean checkNet() {
        this.netType = NewWorkUtils.getNetWorkState(BaseActivity.this);
        if (!isNetConnect()) {
            //网络异常，请检查网络
            showNetDialog();

            msg("网络异常，请检查网络");
        }
        return isNetConnect();
    }

    /**
     * 网络变化之后的类型
     */
    @Override
    public void onChangeListener(int netMobile) {
        // TODO Auto-generated method stub
        this.netType = netMobile;
        if (!isNetConnect()) {
            showNetDialog();
            msg("网络异常，请检查网络");
        } else {
            hideNetDialog();
//            msg("网络恢复正常");
        }
    }

    /**
     * 隐藏设置网络框
     */
    private void hideNetDialog() {
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        alertDialog = null;
    }

    /**
     * 弹出设置网络框
     */
    private void showNetDialog() {
        if (alertDialog == null) {
            alertDialog = new MyAlertDialog(this).builder().setTitle("网络异常")
                    .setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                    }).setPositiveButton("设置", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                            startActivity(intent);
                        }
                    }).setCancelable(false);
        }
        alertDialog.show();
        msg("网络异常，请检查网络");
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect() {
        if (netType == 1) {
            return true;
        } else if (netType == 0) {
            return true;
        } else if (netType == -1) {
            return false;
        }
        return false;
    }

}
